package yxy.game.pm2.bean.db.newDao;

import com.alibaba.fastjson.JSONObject;
import yxy.apple.db.DbManager;
import yxy.game.pm2.bean.db.po.HashCachePo;
import yxy.game.pm2.bean.db.po.TaskPo;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

// 通用的hashset结构数据存储
public class HashCacheDAO {

    // 更新HASH的单条记录（记录存在则更新，不存在则插入）
    public static int updateItem (HashCachePo hashCachePo) {
        String sql = "replace into `hashcache` (`hashkey`, `itemkey`, `value`, `createtime`, `updatetime`) values (?,?,?,?,?)";

        Object[] params = new Object[]{hashCachePo.getHashkey(), hashCachePo.getItemkey(), hashCachePo.getValue(), hashCachePo.getCreatetime(), new Date()};
        return DbManager.instance().executeCommand(sql, params);
    }

    // 更新HASH的单条记录值（记录存在则更新，不存在则插入）
    public static int updateItemV (String hashkey, String itemkey, Object value) {
        String v = JSONObject.toJSONString(value);
        String sql = "replace into `hashcache` (`hashkey`, `itemkey`, `value`, `updatetime`) values (?,?,?,?)";

        Object[] params = new Object[]{hashkey, itemkey, JSONObject.toJSONString(value), new Date()};
        return DbManager.instance().executeCommand(sql, params);
    }

    // 获取HASH的单条记录值（记录存在则更新，不存在则插入）
    public static <T> T getItemV (String hashkey, String itemkey, Class<T> obj) {
        String sql = "select * from `hashcache` where hashkey = ? and itemkey = ? limit 1";

        Object[] params = new Object[]{hashkey, itemkey};
        List<HashCachePo> list = DbManager.instance().executeQueryObjectList(sql, params, HashCachePo.builder);
        if (list == null || list.size() < 1) return null;
        return (T) JSONObject.parseObject(list.get(0).getValue(), obj);
    }

    // 删除HASH某条数据
    public static void deleteItem (String hashkey, String itemkey) {
        String sql = "delete hashcache where hashkey = ? and itemkey = ?";
        DbManager.instance().executeCommand(sql, new Object[]{hashkey, itemkey});
    }

    // 获取整个HASH数据，数据多有性能问题，慎用
    public static HashMap<String, HashCachePo> getMap(String hashkey) {
        String sql = "select * from `hashcache` where hashkey = ?";
        List<HashCachePo> list = DbManager.instance().executeQueryObjectList(sql, new Object[]{hashkey}, HashCachePo.builder);
        return list.stream().collect(Collectors.toMap(HashCachePo::getItemkey, e -> e, (a, b) -> b, HashMap::new));
    }

    // 删除整个HASH
    public static void delete (String hashkey) {
        String sql = "delete hashcache where hashkey = ?";
        DbManager.instance().executeCommand(sql, new Object[]{hashkey});
    }


}
